package com.ygx.zxing.ui

import android.Manifest
import android.app.ProgressDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.hardware.Camera
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Vibrator
import android.text.TextUtils
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.zxing.*
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.qrcode.QRCodeReader
import com.lv.common.base.BaseActivity
import com.lv.common.utils.BitmapUtil
import com.lv.common.utils.DensityUtil
import com.lv.common.utils.StatusBarUtil
import com.ygx.zxing.R
import com.ygx.zxing.camera.CameraManager
import com.ygx.zxing.databinding.ActivityCaptureBinding
import com.ygx.zxing.decoding.CaptureActivityHandler
import com.ygx.zxing.decoding.InactivityTimer
import com.ygx.zxing.decoding.RGBLuminanceSource
import com.ygx.zxing.model.ZxingViewModule
import com.ygx.zxing.utils.CodeUtils
import com.ygx.zxing.view.ViewfinderView
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.io.IOException
import java.util.*

/**
 * 作者： ygx
 * 创建日期：2022/9/1 1:50 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 *
 */
@Route(path = "/captureactivity/captureactivity")
class CaptureActivity : BaseActivity<ActivityCaptureBinding>(), SurfaceHolder.Callback {
    private val viewViewModule: ZxingViewModule by viewModel()

    private val REQUEST_CODE_SCAN_GALLERY = 100
    val INTENT_RESULT = CodeUtils.RESULT_STRING

    private var handler: CaptureActivityHandler? = null
    private var viewfinderView: ViewfinderView? = null
    private var hasSurface = false
    private var decodeFormats: Vector<BarcodeFormat>? = null
    private var characterSet: String? = null
    private var inactivityTimer: InactivityTimer? = null
    private val mediaPlayer: MediaPlayer? = null
    private var playBeep = false
    private val BEEP_VOLUME = 0.10f
    private var vibrate = false
    private val photo_path: String? = null
    private var isOpen = false
    private var parameter: Camera.Parameters? = null
    private var scanBitmap: Bitmap? = null
    private var camera: Camera? = null
    private var flash: TextView? = null

    override fun getLayoutRes() = R.layout.activity_capture
    override fun initView() {
        super.initView()
        StatusBarUtil.immersive(this)
        StatusBarUtil.darkMode(this, true)
        setTopView(mBinding.viewTop)
        /**访问照片权限
         *
         */
        /**访问照片权限
         *
         */
        val checked = ContextCompat.checkSelfPermission(
            this@CaptureActivity, Manifest.permission.CAMERA
        )
        if (checked == PackageManager.PERMISSION_GRANTED) {
        } else {
            ActivityCompat.requestPermissions(
                this@CaptureActivity, arrayOf(Manifest.permission.CAMERA), 1
            )
        }

        CameraManager.init(application)
        viewfinderView = findViewById<View>(R.id.viewfinder_content) as ViewfinderView


        //闪光灯按钮
        mBinding.ivBack.setOnClickListener { finish() }

        //闪光灯按钮
        flash = findViewById<View>(R.id.tv_light) as TextView
        flash?.setOnClickListener(View.OnClickListener { lightOn() })

        //添加相册图片
        mBinding.tvXiangce.setOnClickListener { open_picture() }
        //添加相册图片
        hasSurface = false
        inactivityTimer = InactivityTimer(this)

    }
    private fun setTopView(viewTop: View) {
        val linearParams = viewTop.getLayoutParams() as LinearLayout.LayoutParams
        linearParams.height = DensityUtil.getStatusBarHeight(this)
        viewTop.setLayoutParams(linearParams)
    }


    //打开图片
    private fun open_picture() {
        val innerIntent = Intent(Intent.ACTION_GET_CONTENT)
        innerIntent.type = "image/*"
        val wrapperIntent = Intent.createChooser(innerIntent, "请选择二维码图片")
        startActivityForResult(wrapperIntent, REQUEST_CODE_SCAN_GALLERY)
    }

    /**
     * 闪光灯控制
     */
    private fun lightOn() {
        camera = CameraManager.getCamera()
        parameter = camera?.parameters
        if (!isOpen) {
            parameter?.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH)
            camera?.setParameters(parameter)
            isOpen = true
        } else {  // 关灯
            parameter?.setFlashMode(Camera.Parameters.FLASH_MODE_OFF)
            camera?.setParameters(parameter)
            isOpen = false
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_SCAN_GALLERY ->
                    //获取选中图片的路径
                    data?.let {
                        handleAlbumPic(data)
                    }
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }


    /**
     * 处理选择的图片
     *
     * @param data
     */
    private fun handleAlbumPic(data: Intent) {
        //获取选中图片的路径
        val uri = data.data
        val mProgress = ProgressDialog(this@CaptureActivity)
        mProgress.setMessage("正在扫描...")
        mProgress.setCancelable(false)
        mProgress.show()
        runOnUiThread {
            val result = scanningImage(uri)
            //
//                String realPathFromUri = UriUtil.getRealPathFromUri(CaptureActivity.this, uri);
//                Result result = scanningImage(realPathFromUri);
            mProgress.dismiss()
            if (result != null) {
                val resultIntent = Intent()
                val bundle = Bundle()
                bundle.putString(
                    INTENT_RESULT,
                    result.text
                )

                resultIntent.putExtras(bundle)
                setResult(RESULT_OK, resultIntent)
                finish()
            } else {
                Toast.makeText(this@CaptureActivity, "识别失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 扫描二维码图片的方法
     *
     * @param uri
     * @return
     */
    fun scanningImage(uri: Uri?): Result? {
        if (uri == null) {
            return null
        }
        val hints = Hashtable<DecodeHintType, String?>()
        hints[DecodeHintType.CHARACTER_SET] = "UTF8" //设置二维码内容的编码
        scanBitmap = BitmapUtil.decodeUri(this, uri, 500, 500)
        val source = RGBLuminanceSource(scanBitmap)
        val bitmap1 = BinaryBitmap(HybridBinarizer(source))
        val reader = QRCodeReader()
        try {
            return reader.decode(bitmap1, hints)
        } catch (e: NotFoundException) {
            e.printStackTrace()
        } catch (e: ChecksumException) {
            e.printStackTrace()
        } catch (e: FormatException) {
            e.printStackTrace()
        }
        return null
    }


    override fun onResume() {
        super.onResume()
        val surfaceView = findViewById<View>(R.id.scanner_view) as SurfaceView
        val surfaceHolder = surfaceView.holder
        if (hasSurface) {
            initCamera(surfaceHolder)
        } else {
            surfaceHolder.addCallback(this)
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
        }
        decodeFormats = null
        characterSet = null
        playBeep = true
        val audioService = getSystemService(AUDIO_SERVICE) as AudioManager
        if (audioService.ringerMode != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false
        }
        //        initBeepSound();
        vibrate = true
    }

    override fun onPause() {
        super.onPause()
        if (handler != null) {
            handler?.quitSynchronously()
            handler = null
        }
        CameraManager.get().closeDriver()
    }

    override fun onDestroy() {
        inactivityTimer?.shutdown()
        super.onDestroy()
        //        mScanListener.cancel();

    }


    /**
     * 这里是用相机扫描的处理方法
     */
    fun handleDecode(result: Result, barcode: Bitmap?) {
        inactivityTimer?.onActivity()
        playBeepSoundAndVibrate()
        val resultString = result.text
        if (TextUtils.isEmpty(resultString)) {
            Toast.makeText(this@CaptureActivity, "Scan failed!", Toast.LENGTH_SHORT).show()
        } else {
//            Toast.makeText(CaptureActivity.this, resultString, Toast.LENGTH_SHORT).show();
            val intent = intent
            intent.putExtra(INTENT_RESULT, resultString)
            setResult(RESULT_OK, intent)
            finish()
        }
    }

    private fun initCamera(surfaceHolder: SurfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder)
        } catch (ioe: IOException) {
            return
        } catch (e: RuntimeException) {
            return
        }
        if (handler == null) {
            handler = CaptureActivityHandler(
                this, decodeFormats,
                characterSet
            )
        }
    }

    override fun surfaceChanged(
        holder: SurfaceHolder, format: Int, width: Int,
        height: Int
    ) {
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        if (!hasSurface) {
            hasSurface = true
            initCamera(holder)
        }
    }


    override fun surfaceDestroyed(holder: SurfaceHolder) {
        hasSurface = false
    }

    fun getViewfinderView(): ViewfinderView? {
        return viewfinderView
    }

    fun getHandler(): Handler? {
        return handler
    }

    fun drawViewfinder() {
        viewfinderView?.drawViewfinder()
    }


    private val VIBRATE_DURATION = 200L

    private fun playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start()
        }
        if (vibrate) {
            val vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
            vibrator.vibrate(VIBRATE_DURATION)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1 -> if (permissions.size != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) { //失败
                Toast.makeText(this@CaptureActivity, "请允许相机权限后再试", Toast.LENGTH_SHORT).show()
                finish()
            }
        }
    }
}